package com.springboot.apiexample.annotation;

import com.google.common.util.concurrent.RateLimiter;
import com.springboot.apiexample.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 限流器切面
 * @author NiJo_H
 * @version 1.0
 */
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {

    //默认创建令牌桶10个/S
    private RateLimiter rateLimiter = RateLimiter.create(10);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        RateLimit rateLimit = method.getAnnotation(RateLimit.class);

        if (rateLimit != null) {
            //获取参数、设置桶中令牌
            rateLimiter.setRate(rateLimit.perSecond());
            //判断能否在1秒内得到令牌，如果不能则立即返回false，抛异常
            if(!rateLimiter.tryAcquire(rateLimit.timeOut(), rateLimit.timeOutUnit())){
                log.info("=====    接口并发量过大    =====");
                throw new BusinessException("请求人数太多,请稍后重试!");
            }

        }
        return true;
    }
}
